package nconv.convert;

import nconv.utils.LogCenter;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.ss.formula.eval.ConcatEval;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class WikiPicturesManager implements PicturesManager{

	public static final String MANUAL_PREFIX = "manual-upload-";
	private String docName = "";
	public WikiPicturesManager(String docName) {
		this.docName = docName;
	}

	private int autoPicIdx = 0;
	@Override
	public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches,
	    float heightInches) {

		String fileName = (docName.length() > 0 ? docName + "-" : "") + "pic" + ++autoPicIdx;
		String outFileName = ImageHandler.getOutputDir() + fileName;
		String ext = pictureType.getExtension().toLowerCase();

		if (!ConvertUtils.processImage) {
			return fileName + (ext.length() > 0 ? "." + ext : "");
		}

		try {
			try (FileOutputStream bw = new FileOutputStream(outFileName + "." + ext)) {
				//clpbrd.setContents(stringSelection, null);
				bw.write(content);
			}
		} catch (Exception e) {
			System.err.println(e.getMessage());
		}
		File srcFile = new File(outFileName + "." + ext);
		if (ext.length() == 0 || srcFile.length() == 0) {
			fileName = MANUAL_PREFIX + fileName + (ext.length() == 0 ? ".png" : "." + ext);

			File backupImageFile = new File(ImageHandler.getInputDir() + fileName);
			if (backupImageFile.exists()) {
				srcFile = backupImageFile;
				if (ext.length() == 0) {
					ext = "png";
				}
			}
		}

		if (!srcFile.exists() || srcFile.length() == 0) {
			LogCenter.logWiki(null, LogCenter.DOC_OPERATION.NOTICE, "Need to manually upload file [[Media:" + fileName + "|" + fileName + "]]");
		} else {
			switch (ext) {
				case "png":
				case "jpg":
				case "svg":
					fileName = srcFile.getName();
					break;
				default:
					File dstFile = new File(outFileName + ".png");
					fileName = dstFile.getName();
					if (!ConvertUtils.skipProcessImageIfTargetExists ||
							(ConvertUtils.skipProcessImageIfTargetExists && !dstFile.exists())) {
						ImageHandler.convert(srcFile, dstFile, true);
						srcFile.delete();
					}
			}
		}

		File dstFile = new File(ImageHandler.getOutputDir() + fileName);
		if (dstFile.exists() && dstFile.length() > 0) {
			int width = 0;
			try {
				fileName = fileName + ":" + ImageIO.read(new FileInputStream(dstFile)).getWidth();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
  	
  		return fileName;
	}

}
